package com.hyl.gulimall.order.interceptor;

import com.hyl.common.constant.AuthServerConstant;
import com.hyl.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hyl_marco
 * @data 2022/5/19 - 12:08
 * 1. 拦截器要起作用需要配置
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果请求的路径是查order的状态的，不需要当前是登录状态，因为是服务之间的调用
        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match1 = antPathMatcher.match("/order/order/status/**", requestURI);
        boolean match2 = antPathMatcher.match("/payed/notify", requestURI);
        if(match1 || match2) {
            return true;
        }

        Object userIsLogin = request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if (userIsLogin != null) {
            loginUser.set((MemberRespVo) userIsLogin);
            return true;
        } else {
            //如果目前没有登录用户，重定向到登录页
            request.getSession().setAttribute("msg", "请先进行登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }

    }
}
